package city.spring.modules.checkinfee.controller;

import city.spring.modules.checkinfee.entity.CheckinfeeEntity;
import city.spring.modules.checkinfee.service.CheckinfeeService;
import city.spring.modules.checkinfee.vo.CheckinfeeVO;
import city.spring.modules.expense.entity.ExpenseRecordEntity;
import city.spring.modules.expense.service.ExpenseRecordService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：入院收费
 *
 * @author 谢金婷
 * @date 2020-08-27 10:19:04
 */
@RestController
@RequestMapping("/checkinfee")
public class CheckinfeeController extends ApiController {
    private final CheckinfeeService checkinfeeService;
    private final ExpenseRecordService expenseRecordService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<CheckinfeeEntity, ?>> entityOrderFields;

    public CheckinfeeController(CheckinfeeService checkinfeeService, ExpenseRecordService expenseRecordService) {
        this.checkinfeeService = checkinfeeService;
        this.expenseRecordService = expenseRecordService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(CheckinfeeEntity::getId);
        entityOrderFields.add(CheckinfeeEntity::getOldmanId);
        entityOrderFields.add(CheckinfeeEntity::getCertificate);
        entityOrderFields.add(CheckinfeeEntity::getBedId);
        entityOrderFields.add(CheckinfeeEntity::getAttendanceId);
        entityOrderFields.add(CheckinfeeEntity::getCheckInTime);
        entityOrderFields.add(CheckinfeeEntity::getType);
        entityOrderFields.add(CheckinfeeEntity::getUserId);
        entityOrderFields.add(CheckinfeeEntity::getGmtCreate);
        entityOrderFields.add(CheckinfeeEntity::getGmtModified);
        entityOrderFields.add(CheckinfeeEntity::getDateStart);
        entityOrderFields.add(CheckinfeeEntity::getDateTo);
    }

    /**
     * 获取全部的 <strong>入院收费</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, CheckinfeeEntity entity) {
        LambdaQueryChainWrapper<CheckinfeeEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>入院收费</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"status"}) Pageable pageable, CheckinfeeVO entity) {
//        LambdaQueryChainWrapper<CheckinfeeEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<CheckinfeeEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
        QueryWrapper<? extends CheckinfeeEntity> queryWrapper = buildQuery(entity);
        return success(checkinfeeService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 分页获取 <strong>月度缴费记录</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping("monthPayRecords")
    public Object monthPayRecords(@PageableDefault Pageable pageable, CheckinfeeVO entity) {
        QueryWrapper<? extends CheckinfeeEntity> queryWrapper = buildQuery(entity);
        return success(checkinfeeService.monthPayRecords(MyBatisUtils.toPage(pageable), queryWrapper));
    }


    /**
     * 获取月度缴费的打印信息
     *
     * @param feeid
     * @return
     */
    @GetMapping("monthPayPrintInfo/{feeid}")
    public Object monthPayPrintInfo(@PathVariable String feeid) {
        CheckinfeeVO printInfo = checkinfeeService.monthPayPrintInfo(feeid);
        return success(printInfo);
    }


    /**
     * 分页获取 <strong>入院收费</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping("getMonthlyFeeList")
    public Object monthlyFeelist(@PageableDefault Pageable pageable, CheckinfeeVO entity) {
        QueryWrapper<? extends CheckinfeeEntity> queryWrapper = buildQuery(entity);
        return success(checkinfeeService.monthlyFeelist(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>入院收费</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

//        return success(checkinfeeService.getById(id));
        QueryWrapper<CheckinfeeVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<CheckinfeeVO> records = checkinfeeService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 获取单个老人每月的标准收费（床位费、护理费、定制护理费、餐饮费、水电费）
     *
     * @param id 主键ID
     */
    @GetMapping("monthStandardFee/{id}")
    public Object monthStandardFee(@PathVariable String id) {
        QueryWrapper<CheckinfeeVO> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("t1.id", id);
        List<CheckinfeeVO> records = checkinfeeService.monthlyFeelist2(wrapper2);
        return success(records);
    }

    @GetMapping("monthStandardFee2/{id}")
    public Object monthStandardFee2(@PathVariable String id) {
        QueryWrapper<CheckinfeeVO> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("t1.id", id);
        CheckinfeeVO records = checkinfeeService.monthlyFeelist3(wrapper2);
        return success(records);
    }


    /**
     * 添加一个 <strong>入院收费</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody CheckinfeeEntity entity) {
        checkinfeeService.saveCheckinfee(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 添加一个 <strong>月度收费</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping("monthAdd")
    public Object monthAdd(@RequestBody CheckinfeeEntity entity, @NonNull Principal user) {
        CheckinfeeEntity monthEntity = checkinfeeService.saveMonthfee(entity, user);
        return success(monthEntity);
    }

    /**
     * 修改一个 <strong>入院收费</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody CheckinfeeEntity entity) {
        entity.setId(id);
        checkinfeeService.updateCheckinfee(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>入院收费</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        checkinfeeService.deleteCheckinfee(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>入院收费</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        checkinfeeService.deleteCheckinfee(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 增加多个 <strong>月度缴费</strong>
     *
     * @param oldids 主键ID列表
     */
    @DeleteMapping("addMonthPayRecords")
    public Object addMonthPayRecords(@RequestBody List<String> oldids) {
        checkinfeeService.addMonthPayRecords(oldids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<CheckinfeeEntity> buildLambdaQuery(CheckinfeeEntity entity) {
        LambdaQueryChainWrapper<CheckinfeeEntity> lambdaQuery = checkinfeeService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), CheckinfeeEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOldmanId()), CheckinfeeEntity::getOldmanId, entity.getOldmanId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCertificate()), CheckinfeeEntity::getCertificate, entity.getCertificate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getBedId()), CheckinfeeEntity::getBedId, entity.getBedId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getAttendanceId()), CheckinfeeEntity::getAttendanceId, entity.getAttendanceId());
        lambdaQuery.eq(entity.getCheckInTime() != null, CheckinfeeEntity::getCheckInTime, entity.getCheckInTime());
        lambdaQuery.eq(entity.getType() != null, CheckinfeeEntity::getType, entity.getType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUserId()), CheckinfeeEntity::getUserId, entity.getUserId());
        lambdaQuery.eq(entity.getGmtCreate() != null, CheckinfeeEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, CheckinfeeEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<CheckinfeeEntity> buildQuery(CheckinfeeVO entity) {
        QueryWrapper<CheckinfeeEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanId()), "t1.oldman_id", entity.getOldmanId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanName()), "t2.oldman_name", entity.getOldmanName());
        wrapper.like(StringUtils.isNotBlank(entity.getCertificate()), "t1.certificate", entity.getCertificate());
        wrapper.like(StringUtils.isNotBlank(entity.getBedId()), "t1.bed_id", entity.getBedId());
        wrapper.like(StringUtils.isNotBlank(entity.getBedName()), "t3.name", entity.getBedName());
        wrapper.like(StringUtils.isNotBlank(entity.getAttendanceId()), "t1.attendance_id", entity.getAttendanceId());
        wrapper.like(StringUtils.isNotBlank(entity.getAttendanceName()), "t4.title", entity.getAttendanceName());
        wrapper.eq(entity.getCheckInTime() != null, "t1.check_in_time", entity.getCheckInTime());
        wrapper.eq(entity.getIsInvalid() != null, "t1.is_invalid", entity.getIsInvalid());
        wrapper.eq(entity.getCategory() != null, "t1.category", entity.getCategory());
        wrapper.eq(entity.getType() != null, "t1.type", entity.getType());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "t1.user_id", entity.getUserId());
//        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "t5.name", entity.getUserName());
        wrapper.like(StringUtils.isNotBlank(entity.getUserName()), "t5.username", entity.getUserName());
        wrapper.eq(entity.getGmtCreate() != null, "t1.gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "t1.gmt_modified", entity.getGmtModified());
        return wrapper;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<CheckinfeeEntity> buildQuery2(CheckinfeeVO entity) {
        QueryWrapper<CheckinfeeEntity> wrapper2 = new QueryWrapper<>();
        wrapper2.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper2.like(StringUtils.isNotBlank(entity.getOldmanId()), "t1.oldman_id", entity.getOldmanId());
        wrapper2.like(StringUtils.isNotBlank(entity.getOldmanName()), "t6.oldman_name", entity.getOldmanName());
        wrapper2.like(StringUtils.isNotBlank(entity.getCertificate()), "t1.certificate", entity.getCertificate());
        wrapper2.like(StringUtils.isNotBlank(entity.getBedId()), "t1.bed_id", entity.getBedId());
        wrapper2.eq(entity.getBedFee() != null, "t2.fee", entity.getBedFee());
        wrapper2.eq(entity.getNurseFee() != null, "t3.attendance_fee", entity.getNurseFee());
        wrapper2.eq(entity.getCustomNurseFee() != null, "t3.privatecustomization_fee", entity.getCustomNurseFee());
        wrapper2.eq(entity.getMealFee() != null, "t4.cost", entity.getMealFee());
        wrapper2.eq(entity.getWaterFee() != null, "t5.cost", entity.getWaterFee());
        wrapper2.eq(entity.getTotalMount() != null, "t2.fee+t3.attendance_fee+t3.privatecustomization_fee+t4.cost+t5.cost", entity.getTotalMount());
        wrapper2.like(StringUtils.isNotBlank(entity.getOldmanName()), "t6.oldman_name", entity.getOldmanName());
        wrapper2.like(StringUtils.isNotBlank(entity.getAttendanceId()), "t1.attendance_id", entity.getAttendanceId());
        wrapper2.eq(entity.getCheckInTime() != null, "t1.check_in_time", entity.getCheckInTime());
        wrapper2.eq(entity.getType() != null, "t1.type", entity.getType());
        wrapper2.like(StringUtils.isNotBlank(entity.getUserId()), "t1.user_id", entity.getUserId());
        wrapper2.eq(entity.getGmtCreate() != null, "t1.gmt_create", entity.getGmtCreate());
        wrapper2.eq(entity.getGmtModified() != null, "t1.gmt_modified", entity.getGmtModified());
        return wrapper2;
    }

    @GetMapping("/getCheckfeeByolamanId")
    public Object getCheckfeeByolamanId(String oldmanId) {
        return success(checkinfeeService.getCheckfeeByolamanId(oldmanId));
    }

    /**
     * 获取最新的缴费记录
     *
     * @param personId
     * @return
     */
    @GetMapping("/getLatestPayRecord/{personId}")
    public Object getLatestPayRecord(@PathVariable String personId) {
        return success(checkinfeeService.getLatestPayRecord(personId));
    }

    /**
     * 退住结算：获取已交费用记录（入院缴费/月度缴费）
     *
     * @param personId
     * @return
     */
    @GetMapping("settlement/payRecords/{personId}/{leaveDate}")
    public Object settlementPayRecords(@PathVariable String personId, @PathVariable Date leaveDate) {
        List<CheckinfeeVO> records = checkinfeeService.settlementPayRecords(personId, leaveDate);
        return success(records);
    }

    /**
     * 退住结算：获取 某个老人 是否需要补交费，补交到哪个月
     *
     * @param personId
     * @return
     */
    @GetMapping("settlement/isAlreadyPayBeforeLeaveMonth/{personId}/{leaveDate}")
    public Object isAlreadyPayBeforeLeaveMonth(@PathVariable String personId, @PathVariable Date leaveDate) {
        Object[] objs = checkinfeeService.isAlreadyPayBeforeLeaveMonth(personId, leaveDate);
        return success(objs);
    }
//    /**
//     * 结算：判断退住当月有无交费
//     *
//     * @param oldmanId
//     * @return
//     */
//    @GetMapping("settlement/leaveMonthPayOrNot/{oldmanId}")
//    public Object getLeaveMonthPayOrNot(@PathVariable String oldmanId) {
//        Object objs = checkinfeeService.getLeaveMonthPayOrNot(oldmanId);
//        return success(objs);
//    }

    /**
     * 退住结算：获取结算结果
     *
     * @param paySum
     * @param billSum
     * @param balanceMount
     * @param depositMount
     * @param otherNeed
     * @param fiveTypeFee
     * @return
     */
    @GetMapping("settlement/settlementResults/{paySum}/{billSum}/{balanceMount}/{depositMount}/{otherNeed}/{fiveTypeFee}")
    public Object isAlreadyPayBeforeLeaveMonth(@PathVariable BigDecimal paySum, @PathVariable BigDecimal billSum, @PathVariable BigDecimal balanceMount, @PathVariable BigDecimal depositMount,
                                               @PathVariable BigDecimal otherNeed, @PathVariable BigDecimal fiveTypeFee) {
        Object[] objs = checkinfeeService.settlementResults(paySum, billSum, balanceMount, depositMount, otherNeed, fiveTypeFee);
        return success(objs);
    }

    /**
     * 结算账单：已交账单 根据结算记录Id，对应的老人id，获取入住记录中老人最新的的入住日期、退住日期，再从缴费录checkinfee获取这两个日期间的记录，再由费用记录expense_record表获取金额信息
     *
     * @param expecseId
     * @return
     */
    @GetMapping("payRecords/{expecseId}")
    public Object getpayRecords(@PathVariable String expecseId) {
        // 根据结算记录id 得到该费用记录相关的老人ID
        ExpenseRecordEntity expenseRecordEntity = expenseRecordService.getById(expecseId);
        String oldmanId = expenseRecordEntity.getOldmanId();
        return success(checkinfeeService.getpayRecords(oldmanId));
    }
}